#include <iostream>
#include <string>
#include "socket.hpp"
#include "protocol.hpp"
#include <time.h>
using namespace std;

void usage(string arg) {
    cerr << "Usage: " << arg << " <ip>" << " <port>" << endl;
    exit(1);
}

int main(int argc, char *argv[]) {
    if(argc != 3) {
        usage(argv[0]);
    }
    srand(time(nullptr));
    string ip = argv[1];
    uint16_t port = atoi(argv[2]);
    Socket sock;
    sock.socket();
    sock.connect(ip, port);
    int cnt = 2;
    const string ops = "+-*^&";
    while(cnt--) {
        int x = rand() % 10;
        int y = rand() % 10;
        char op = ops[rand() % ops.size()];
        request req = {x, y, op};
        string msg;
        req.print();
        req.serializer(&msg);
        if(!encapsulate(&msg)) {
            continue;
        }
        
        write(sock.get_sockfd(), msg.c_str(), msg.size());
        sleep(1);
        char buffer[1024];
        ssize_t n = read(sock.get_sockfd(), buffer, sizeof(buffer) - 1);
        if(n > 0) {
            buffer[n] = '\0';
            cout << "client received a packet: " << buffer << endl;
            string packet = buffer;
            string data;
            if(!decapsulate(&data, packet)) {
                continue;
            }
            response res;
            res.deserializer(data);
            cout << "client received a response: " << res.get_result() << endl << endl;
        }
        
    }
    return 0; 
}